package edu.zut.util;

import java.sql.*;

/**
 * JDBC操作模板
 */
public class DBUtils {

    static final String URL="jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    static final String NAME="root";
    static String PSW = "qwer1234";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    static Connection connection = null;
    static PreparedStatement statement = null;
    static ResultSet resultSet = null;
    /**
     * 数据库连接的获取
     * @return 数据库连接
     */
    public static Connection getConn(){
        try {
            connection = DriverManager.getConnection(URL,NAME,PSW);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 查询的统一封装：
     * @param sql: 查询的sql语句
     * @param objs: sql中需要填充的数据
     * @return ResultSet: 结果集
     */
    public static ResultSet query(String sql,Object... objs){
        connection = getConn();
        //预处理sql
        try {
            statement = connection.prepareStatement(sql);
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            //执行sql
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 增删改的封装
     * @param sql: 查询的sql语句
     * @param objs: sql中需要填充的数据
     * @return int: 受影响的行数
     */
    public static int update(String sql,Object... objs){
        connection = getConn();
        int result = 0;
        try {
            //预处理sql
            statement = connection.prepareStatement(sql);
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            //执行sql
            result = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            free();
        }
        return result;
    }

    //如果想对结果集进行统一再次封装，可以尝试使用反射完成


    /**
     * 资源的关闭
     */
    public static void free(){
        if (null != resultSet){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
